
import { connectionManger } from "./connectionmanager";
import { mysqlTransaction } from "./mysqltransaction";

import { Transaction } from "./transaction";

/**
 * 获取连接
 * @returns 连接对象
 */
export async function getConnection(): Promise<any> {
    return await connectionManger.createConnection()
}

/**
 * 用Nesting level来标识当前嵌套的级别
 * 嵌套级别为1，还没有嵌套，那就是顶层事务
 * 嵌套级别大于1，有嵌套，创建savepoint，子事务提交释放保存点，回滚则回滚到保存点。
 */

/**
 * 开始事务
 */
export async function beginTransction() {
    let conn = await getConnection()
    let tx : mysqlTransaction = connectionManger.getTransaction(conn)
    // 开始一个事务，事务的嵌套级别加1
    ++Transaction.nestingLevel
    
    // 如果事务的嵌套级别为1
    if (Transaction.nestingLevel === 1) {
        // 实际开始一个事务
        await tx.begin();
    } 
    // // 如果允许嵌套事务
    else if (Transaction.isNest) {
        tx.createSavepoint(Transaction.getSavePointName())
    }
}


/**
 * 提交事务
 */
export async function commitTransaciton(): Promise<void> {
    const conn = await getConnection();
    let tx : mysqlTransaction = connectionManger.getTransaction(conn)
    
    // const transaction = new Transaction(conn);
    // transaction.tx = tx
    //嵌套级别为1  实际事务提交
    if (Transaction.nestingLevel === 1) {
        await tx.commit();
    } 
    else if(Transaction.isNest){
        
        await tx.releaseSavepoint(Transaction.getSavePointName());
    }
    Transaction.nestingLevel--;
}

/**
 * 回滚事务
 */
export async function rollbackTransaction() {
    const conn = await getConnection();
    let tx : mysqlTransaction = connectionManger.getTransaction(conn)
    
    //嵌套级别为1  实际事务回滚
    
    if (Transaction.nestingLevel === 1) {
        await tx.rollback();
    } 
    else if(Transaction.isNest){
        await tx.rollbackToSavepoint(Transaction.getSavePointName());
    }
    Transaction.nestingLevel--;
    
}

/**
 * 关闭连接
 * 
 */
export async function closeConnection() {
    // const conn = await getConnection();
    // await connectionManger.close(conn);
    connectionManger.release()
}